package com.zzstm.eduorder.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zzstm.commonUtils.JwtUtils;
import com.zzstm.commonUtils.R;
import com.zzstm.eduorder.entity.Order;
import com.zzstm.eduorder.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 订单 前端控制器
 * </p>
 *
 * @author testjava
 * @since 2022-11-20
 */
@RestController
@RequestMapping("/eduorder/order")
@CrossOrigin
public class OrderController {

    @Autowired
    private OrderService orderService;

    //生成订单
    @PostMapping("/createOrder/{courseId}")
    public R createOrder(@PathVariable String courseId, HttpServletRequest request){
        String userId = JwtUtils.getMemberIdByJwtToken(request);
        if (StringUtils.isEmpty(userId)){
            return R.error().message("请先登录");
        }
        String orderNo = orderService.createOrder(courseId,userId);
        if (orderNo == null){
            return R.error().message("再点一次试试");
        }
        return R.ok().data("orderId",orderNo);
    }

    //根据订单id查询订单
    @GetMapping("/getOrderInfo/{orderId}")
    public R getOrderInfo(@PathVariable String orderId){
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        wrapper.eq("order_no",orderId);
        Order order = orderService.getOne(wrapper);
        return R.ok().data("order",order);
    }

    //根据课程id和用户id查询订单表订单状态
    @GetMapping("/isBuyCourse/{courseId}/{userId}")
    public boolean isBuyCourse(@PathVariable String courseId,@PathVariable String userId){
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        wrapper.eq("course_id",courseId);
        wrapper.eq("member_id",userId);
        wrapper.eq("status",1);
        int result = orderService.count(wrapper);
        return result > 0;
    }

}

